package com.caigou.modules.forum.ui.forum

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.CommentItemAdapter
import com.caigou.comm.base.adapter.PrizeBallItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bean.OpenPrizeVoBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.viewmodel.RewardViewModel
import com.caigou.comm.base.widget.BuyFlowerDialog
import com.caigou.comm.base.widget.ReportDialog
import com.caigou.comm.base.widget.RewardDialog
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.DareItemAdapter
import com.caigou.modules.forum.adpter.PacketRecordItemAdapter
import com.caigou.modules.forum.bean.*
import com.caigou.modules.forum.databinding.ActivityPostBinding
import com.caigou.modules.forum.viewmodel.*
import com.caigou.modules.forum.widget.PacketOpenDialog
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/08
 */
@Route(path = RouterPath.Forum.PAGE_FORUM_POST)
@AndroidEntryPoint
class ForumPostActivity : BaseActivity() {

    private lateinit var binding: ActivityPostBinding
    private val postViewModel: PostViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()
    private val followView: FollowViewModel by viewModels()
    private val rewardViewModel: RewardViewModel by viewModels()
    private val reportViewModel: ReportViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.POST_ID)
    var postId: Int = 0

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private val banners: MutableList<String> by lazy {
        mutableListOf()
    }

    private val urls: MutableList<String> by lazy {
        mutableListOf()
    }

    private val mAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    private val prizeAdapter: PrizeBallItemAdapter by lazy {
        PrizeBallItemAdapter(mutableListOf())
    }

    private val dareAdapter: DareItemAdapter by lazy {
        DareItemAdapter(mutableListOf())
    }

    private val packetRecordItemAdapter: PacketRecordItemAdapter by lazy {
        PacketRecordItemAdapter(mutableListOf())
    }

    private val commentItemAdapter: CommentItemAdapter by lazy {
        CommentItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPostBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.postLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.postSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchPostDetail()
            }
        }

        commentItemAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                commentItemAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.postLayoutPostContent.postContentRecyclerViewComment.run {
            layoutManager = LinearLayoutManager(this@ForumPostActivity)
            adapter = commentItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumPostActivity))
        }

        commentItemAdapter.setOnItemChildClickListener { _, view, position ->
            val item = commentItemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Forum.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setCommentLike(item.replyId, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Forum.PAGE_COMMENT_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_iv_report -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        with(ReportDialog(this)) {
                            btnConfirm.setOnClickListener {
                                if (TextUtils.isEmpty(reportCause)) {
                                    showToast("举报原因不能为空！")
                                    return@setOnClickListener
                                }
                                reportViewModel.setReplyReport(
                                    AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId,
                                    reportCause, item.replyId, 5
                                )
                                dismiss()
                            }
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.postLayoutPostContent.postContentRecyclerViewRedpackRecord.run {
            layoutManager = LinearLayoutManager(this@ForumPostActivity)
            adapter = packetRecordItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumPostActivity))
        }

        binding.postLayoutPostContent.postContentRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.postLayoutPostContent.postContentBtnSequential.id -> 1
                binding.postLayoutPostContent.postContentBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            fetchCommentList()
        }

        binding.postTvBack.setOnClickListener {
            finish()
        }

        binding.postLayoutPostFooter.postFooterLlShare.setOnClickListener {
            val bitmap = binding.postLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentList()
        }

        fetchPostDetail()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(postViewModel.postDetailLiveData, ::handleGetPostDetail)
        observe(postViewModel.commentListLiveData, ::handleGetCommentList)
        observe(likeViewModel.postLikeLiveData, ::handleSetPostLike)
        observe(likeViewModel.replyLikeLiveData, ::handleSetCommentLike)
        observe(followView.followLiveData, ::handleSetFollow)
        observe(rewardViewModel.buyFlowerLiveData, ::handleBuyFlower)
        observe(rewardViewModel.rewardLiveData, ::handleSetReward)
        observe(reportViewModel.postReportLiveData, ::handleSetReport)
        observe(reportViewModel.replyReportLiveData, ::handleSetReport)
    }

    private fun handleGetPostDetail(result: Resource<PostDetailBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取帖子详细信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    binding.postTvTitle.text = "第${result.data!!.period}期"
                    handleHeaderUI(this)
                    handleContentUI(this)
                    handleFooterUI(this)
                }
            }
        }
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取帖子评论异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.postLayoutPostContent.postContentLlEmptyComment.visibility = View.VISIBLE
                    binding.postLayoutPostContent.postContentRecyclerViewComment.visibility = View.GONE
                    return
                }
                if (result.data!!.list.isEmpty()) {
                    binding.postLayoutPostContent.postContentLlEmptyComment.visibility = View.VISIBLE
                    binding.postLayoutPostContent.postContentRecyclerViewComment.visibility = View.GONE
                } else {
                    binding.postLayoutPostContent.postContentLlEmptyComment.visibility = View.GONE
                    binding.postLayoutPostContent.postContentRecyclerViewComment.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    commentItemAdapter.setList(result.data!!.list)
                } else {
                    commentItemAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    commentItemAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSetPostLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchPostDetail()
                }
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.postSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchPostDetail()
                }
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                fetchPostDetail()
            }
        }
    }

    private fun handleSetReward(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("打赏用户异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleBuyFlower(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("购买小红花异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleSetReport(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("举报异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun handleHeaderUI(bean: PostDetailBean) {
        with(binding.postLayoutPostHeader) {
            if (TextUtils.isEmpty(bean.headImg)) {
                postHeaderIvAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.headImg, postHeaderIvAvatar)
            }
            postHeaderIvAvatar.setOnClickListener {
                ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                    .withString(AppConstants.USER_ID, bean.userId)
                    .navigation()
            }

            postHeaderTvNickname.text = bean.nickName
            if (bean.vip == 1) {
                postHeaderTvNickname.setTextColor(Color.parseColor("#FE6880"))
            } else {
                postHeaderTvNickname.setTextColor(Color.parseColor("#505050"))
            }
            postHeaderTvTime.text = bean.createTime
            postHeaderIvLv.setImageResource(levelImage(bean.level))
            postHeaderTvNiceNum.text = bean.winNicePoint.toString()
            postHeaderTvFansNum.text = bean.fansCount.toString()
            postHeaderTvFocusNum.text = bean.followCount.toString()
            postHeaderTvGrowthNum.text = bean.levelGrowthValue.toString()

            postHeaderBtnFocus.visibility = if (bean.concern) {
                View.GONE
            } else {
                View.VISIBLE
            }
            postHeaderBtnFocus.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    followView.setFollow(AppBackgroundInfo.instance.userBean!!.userId, bean.userId)
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            postHeaderBtnHistory.setOnClickListener {
                ARouter.getInstance().build(RouterPath.Forum.PAGE_POST_REPLY)
                    .withObject(AppConstants.POST_DETAIL_BEAN, bean)
                    .navigation()
            }

            postHeaderBtnHistory.setOnClickListener {
                ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_HISTORY_POST)
                    .withInt(AppConstants.FORUM_TYPE, bean.type)
                    .withString(AppConstants.USER_ID, bean.userId)
                    .navigation()
            }

            binding.postLayoutPostHeader.postHeaderIvReward.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    with(RewardDialog(this@ForumPostActivity, bean.headImg, object : RewardDialog.IRewardClickCallback {
                        override fun onChargeMoney() {
                            showToast("暂未开放，敬请期待")
                        }

                        override fun onChargeFlower() {
                            val dialog = BuyFlowerDialog(this@ForumPostActivity)
                            dialog.apply {
                                btnConfirm.setOnClickListener {
                                    rewardViewModel.buyFlower(AppBackgroundInfo.instance.userBean!!.userId, flowerNum)
                                    dismiss()
                                }
                                show()
                            }
                        }

                        override fun onReward(type: Int, num: Int) {
                            rewardViewModel.setReward(type, num, AppBackgroundInfo.instance.userBean!!.userId, bean.userId)
                        }

                    })) {
                        show()
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }
        }

        binding.postIvReport.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                with(ReportDialog(this)) {
                    btnConfirm.setOnClickListener {
                        if (TextUtils.isEmpty(reportCause)) {
                            showToast("举报原因不能为空！")
                            return@setOnClickListener
                        }
                        reportViewModel.setPostReport(AppBackgroundInfo.instance.userBean!!.userId, bean.userId, reportCause, bean.id, 4)
                        dismiss()
                    }
                    show()
                }
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }
    }

    private fun handleContentUI(bean: PostDetailBean) {
        with(binding.postLayoutPostContent) {
            postContentTvTitle.text = bean.title
            postContentTvContent.text = bean.content
            if (bean.imgs.size > 0) {
                postContentNgvDisplay.run {
                    visibility = View.VISIBLE
                    setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 200)
                    mAdapter.dataList = bean.imgs
                    mAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
                        override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {

                        }

                        override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                            data?.apply {
                                showImgsPreview(this@ForumPostActivity, bean.imgs, bean.imgs.indexOf(this))
                            }
                        }

                        override fun onImageDeleted(position: Int, data: String?) {
                        }
                    })
                    adapter = mAdapter
                }
            }

            binding.postLayoutPostContent.postContentTvNotice.text = bean.notice

            handlePrize(bean.openPrizeVo)
            handleDare(bean.dareResultVo)
            handlePacket(bean)
            handleRank(bean)
            handleBanner(bean.adList)
        }
    }

    private fun handleFooterUI(bean: PostDetailBean) {
        with(binding.postLayoutPostFooter) {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                    postFooterIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
                } else {
                    ImageLoader.loadCircle(this@ForumPostActivity, AppBackgroundInfo.instance.userBean!!.headImg, postFooterIvMyAvatar)
                }
            } else {
                postFooterIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            }

            postFooterTvLikeNum.text = bean.nicePointCount.toString()
            if (bean.like) {
                postFooterIvLike.setImageResource(R.drawable.img_forum_like)
                postFooterTvLikeNum.setTextColor(Color.parseColor("#FE6880"))
            } else {
                postFooterIvLike.setImageResource(R.drawable.img_forum_unlike)
                postFooterTvLikeNum.setTextColor(Color.parseColor("#505050"))
            }
            postFooterLlLike.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    if (bean.like) {
                        showToast("您已经点过赞了")
                    } else {
                        likeViewModel.setPostLike(bean.id, AppBackgroundInfo.instance.userBean!!.userId, bean.userId)
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            postFooterTvCommentNum.text = bean.replyCount.toString()
            postFooterLlComment.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    ARouter.getInstance().build(RouterPath.Forum.PAGE_POST_REPLY)
                        .withObject(AppConstants.POST_DETAIL_BEAN, bean)
                        .navigation()
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }

            postFooterBtnReply.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    ARouter.getInstance().build(RouterPath.Forum.PAGE_POST_REPLY)
                        .withObject(AppConstants.POST_DETAIL_BEAN, bean)
                        .navigation()
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }

            }

            postFooterLlReward.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    with(RewardDialog(this@ForumPostActivity, bean.headImg, object : RewardDialog.IRewardClickCallback {
                        override fun onChargeMoney() {
                            showToast("暂未开放，敬请期待")
                        }

                        override fun onChargeFlower() {
                            val dialog = BuyFlowerDialog(this@ForumPostActivity)
                            dialog.apply {
                                btnConfirm.setOnClickListener {
                                    rewardViewModel.buyFlower(AppBackgroundInfo.instance.userBean!!.userId, flowerNum)
                                    dismiss()
                                }
                                show()
                            }
                        }

                        override fun onReward(type: Int, num: Int) {
                            rewardViewModel.setReward(type, num, AppBackgroundInfo.instance.userBean!!.userId, bean.userId)
                        }

                    })) {
                        show()
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }
        }
    }

    private fun handlePrize(bean: OpenPrizeVoBean) {
        with(binding.postLayoutPostContent) {
            if (bean.prizeList.isNullOrEmpty()) {
                postContentLlPrize.visibility = View.GONE
                postContentTvPrizeTitle.visibility = View.GONE
            } else {
                postContentLlPrize.visibility = View.VISIBLE
                postContentTvPrizeTitle.visibility = View.VISIBLE

                postContentTvPrizeTitle.text = "第${bean.period}期开奖结果"
                postContentRecyclerViewPrize.run {
                    layoutManager = GridLayoutManager(this@ForumPostActivity, 6)
                    adapter = prizeAdapter
                    itemAnimator = DefaultItemAnimator()
                    addItemDecoration(SpaceItemDecoration(this@ForumPostActivity))
                }

                val size = bean.prizeList.size
                val balls = bean.prizeList.slice(0..size - 2)
                prizeAdapter.setList(balls)
                val lastBall = bean.prizeList[size - 1]
                postContentPrizeTvNum.text = lastBall.number
                postContentPrizeTvNum.setBackgroundResource(prizeBallColor(lastBall.numberColor))
                postContentPrizeTvDesc.text = lastBall.animalName
            }
        }
    }

    private fun handleDare(bean: DareResultVoBean) {
        with(binding.postLayoutPostContent) {
            if (bean.dareResultList.isNullOrEmpty()) {
                postContentLlDare.visibility = View.GONE
            } else {
                postContentLlDare.visibility = View.VISIBLE
                postContentTvDareTitle.text = "参赛帖 第${bean.period}期${dareTypeName(bean.dareType)}"
                postContentRecyclerViewDare.run {
                    layoutManager = LinearLayoutManager(this@ForumPostActivity)
                    adapter = dareAdapter
                    itemAnimator = DefaultItemAnimator()
                    addItemDecoration(SpaceItemDecoration(this@ForumPostActivity))
                }
                dareAdapter.setList(bean.dareResultList)
                postContentTvMoney.text = bean.msg
                if (bean.statusAward == 1) {
                    postContentTvMoney.setTextColor(Color.parseColor("#FE6880"))
                } else {
                    postContentTvMoney.setTextColor(Color.parseColor("#505050"))
                }
            }
        }
    }

    private fun handlePacket(bean: PostDetailBean) {
        if (bean.redPacketId == 0) {
            binding.postLayoutPostContent.postContentLlRedpack.visibility = View.GONE
        } else {
            binding.postLayoutPostContent.postContentLayoutRedpack.redpackTvDesc2.text = if (bean.redPacketStatus == 0) {
                "领取红包"
            } else {
                "红包已领取"
            }
            binding.postLayoutPostContent.postContentLlRedpack.visibility = View.VISIBLE
            binding.postLayoutPostContent.postContentLayoutRedpack.redpackCvContainer.setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    if (bean.redPacketStatus == 0) {
                        with(PacketOpenDialog(this, bean.headImg, bean.nickName) {
                            ARouter.getInstance().build(RouterPath.Forum.PAGE_PACKET)
                                .withInt(AppConstants.RED_PACKET_ID, bean.redPacketId)
                                .navigation()
                        }) {
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Forum.PAGE_PACKET)
                            .withInt(AppConstants.RED_PACKET_ID, bean.redPacketId)
                            .navigation()
                    }
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }
            binding.postLayoutPostContent.postContentLayoutRedpack.redpackTvNickname.text = "${bean.nickName}的红包"

            packetRecordItemAdapter.setList(bean.redPacketRecordList)
        }
    }

    private fun handleRank(bean: PostDetailBean) {
        with(binding.postLayoutPostContent) {
            postContentLlGiftContainer.visibility = View.VISIBLE

            postContentTvGiftMoney.text = bean.giftMoneyTotal.toString()
            postContentTvGiftFlower.text = bean.giftFlowerTotal.toString()
            postContentTvGiftMore.setOnClickListener {
                ARouter.getInstance().build(RouterPath.Forum.PAGE_GIFT_RANK)
                    .withString(AppConstants.USER_ID, bean.userId)
                    .navigation()
            }
            when (bean.giftRankList.size) {
                1 -> {
                    handleRank1(bean.giftRankList[0])
                }
                2 -> {
                    handleRank1(bean.giftRankList[0])
                    handleRank2(bean.giftRankList[1])
                }
                3 -> {
                    handleRank1(bean.giftRankList[0])
                    handleRank2(bean.giftRankList[1])
                    handleRank3(bean.giftRankList[2])
                }
                4 -> {
                    handleRank1(bean.giftRankList[0])
                    handleRank2(bean.giftRankList[1])
                    handleRank3(bean.giftRankList[2])
                    handleRank4(bean.giftRankList[3])
                }
                5 -> {
                    handleRank1(bean.giftRankList[0])
                    handleRank2(bean.giftRankList[1])
                    handleRank3(bean.giftRankList[2])
                    handleRank4(bean.giftRankList[3])
                    handleRank5(bean.giftRankList[4])
                }
            }
        }
    }

    private fun handleRank1(bean: PostRankItemBean) {
        with(binding.postLayoutPostContent) {
            if (TextUtils.isEmpty(bean.senderUserHeadImg)) {
                postContentLayoutRank.postRankIvRank1Avatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.senderUserHeadImg, postContentLayoutRank.postRankIvRank1Avatar)
            }
            postContentLayoutRank.postRankTvRank1Nickname.text = bean.senderUserNickName
            postContentLayoutRank.postRankTvRank1Num.text = bean.charmValue.toString()
        }
    }

    private fun handleRank2(bean: PostRankItemBean) {
        with(binding.postLayoutPostContent) {
            if (TextUtils.isEmpty(bean.senderUserHeadImg)) {
                postContentLayoutRank.postRankIvRank2Avatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.senderUserHeadImg, postContentLayoutRank.postRankIvRank2Avatar)
            }
            postContentLayoutRank.postRankTvRank2Nickname.text = bean.senderUserNickName
            postContentLayoutRank.postRankTvRank2Num.text = bean.charmValue.toString()
        }
    }

    private fun handleRank3(bean: PostRankItemBean) {
        with(binding.postLayoutPostContent) {
            if (TextUtils.isEmpty(bean.senderUserHeadImg)) {
                postContentLayoutRank.postRankIvRank3Avatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.senderUserHeadImg, postContentLayoutRank.postRankIvRank3Avatar)
            }
            postContentLayoutRank.postRankTvRank3Nickname.text = bean.senderUserNickName
            postContentLayoutRank.postRankTvRank3Num.text = bean.charmValue.toString()
        }
    }

    private fun handleRank4(bean: PostRankItemBean) {
        with(binding.postLayoutPostContent) {
            if (TextUtils.isEmpty(bean.senderUserHeadImg)) {
                postContentLayoutRank.postRankIvRank4Avatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.senderUserHeadImg, postContentLayoutRank.postRankIvRank4Avatar)
            }
            postContentLayoutRank.postRankTvRank4Nickname.text = bean.senderUserNickName
            postContentLayoutRank.postRankTvRank4Num.text = bean.charmValue.toString()
        }
    }


    private fun handleRank5(bean: PostRankItemBean) {
        with(binding.postLayoutPostContent) {
            if (TextUtils.isEmpty(bean.senderUserHeadImg)) {
                postContentLayoutRank.postRankIvRank5Avatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@ForumPostActivity, bean.senderUserHeadImg, postContentLayoutRank.postRankIvRank5Avatar)
            }
            postContentLayoutRank.postRankTvRank5Nickname.text = bean.senderUserNickName
            postContentLayoutRank.postRankTvRank5Num.text = bean.charmValue.toString()
        }
    }

    private fun handleBanner(list: MutableList<PostDetailAdBean>) {
        banners.clear()
        urls.clear()
        list.forEach {
            banners.add(it.img)
            urls.add(it.url)
        }
        with(binding.postLayoutPostContent.postContentBagBanner) {
            setDelegate { _, _, _, position ->
                openBrowser(urls[position])
            }
            setAdapter { _, itemView, model, _ ->
                ImageLoader.load(this@ForumPostActivity, model as String?, itemView as ImageView)
            }
            setAutoPlayAble(banners.size > 1)
            setData(banners, null)
        }
    }

    private fun fetchPostDetail() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        postViewModel.getPostDetail(postId, userId)
        fetchCommentList()
    }

    private fun fetchCommentList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        postViewModel.getCommentList(page, limit, postId, sort, userId)
    }
}